package com.lznAdmin.security.config;

import cn.hutool.json.JSONUtil;
import com.lznAdmin.base.common.util.JwtUtil;
import com.lznAdmin.base.lznAdminResult;
import com.lznAdmin.properties.SecurityProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;


@Component("customAuthenticationSuccessHandler")
//public class CustomAuthenticationSuccessHandler  implementse AuthenticationSuccessHandler

public class CustomAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    SecurityProperties securityProperties;

    @Autowired
    JwtUtil jwtUtil;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {

        response.setContentType("application/json;charset=UTF-8");
        ServletOutputStream outputStream = response.getOutputStream();

        logger.info("rememberMe = {}", request.getParameter("rememberMe"));

        String Jwt = "";
        if (request.getParameter("rememberMe") != null) {
            // 生成7天 jwt，并放置到请求头中
            Jwt = jwtUtil.generateToken(authentication.getName(), 604800);
            response.setHeader(jwtUtil.getHeader(), Jwt);
        } else {
            // 生成3小时jwt，并放置到请求头中
            Jwt = jwtUtil.generateToken(authentication.getName());
            response.setHeader(jwtUtil.getHeader(), Jwt);
        }
        logger.info("response: {}", Jwt);
        jwtUtil.loginList(Jwt);

        lznAdminResult result = lznAdminResult.ok("认证成功");

        outputStream.write(JSONUtil.toJsonStr(result).getBytes(StandardCharsets.UTF_8));

        outputStream.flush();
        outputStream.close();
    }

}
